"use client";

import React, { useState, useRef, useEffect } from "react";
import Typography from "antd/es/typography";
import Input from "antd/es/input";
import Button from "antd/es/button";
import Pagination from "antd/es/pagination";
import Empty from "antd/es/empty";
import Dropdown from "antd/es/dropdown";
import message from "antd/es/message";
import Tooltip from "antd/es/tooltip";
import SearchOutlined from "@ant-design/icons/SearchOutlined";
import PlusOutlined from "@ant-design/icons/PlusOutlined";
import PlayCircleOutlined from "@ant-design/icons/PlayCircleOutlined";
import PauseCircleOutlined from "@ant-design/icons/PauseCircleOutlined";
import MoreOutlined from "@ant-design/icons/MoreOutlined";
import EditOutlined from "@ant-design/icons/EditOutlined";
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
import DownloadOutlined from "@ant-design/icons/DownloadOutlined";
import Waveform from "../components/Waveform";
import styles from "./audio.module.css";

const { Title } = Typography;
const { Search } = Input;

// 模拟音频数据
const mockAudioData = [
  {
    id: "1",
    title: "欢迎语音提示",
    duration: 35, // 秒
    size: "320KB",
    format: "MP3",
    createTime: "2023-05-15",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
  },
  {
    id: "2",
    title: "错误提示音效",
    duration: 12,
    size: "128KB",
    format: "MP3",
    createTime: "2023-06-22",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
  },
  {
    id: "3",
    title: "成功操作提示音",
    duration: 8,
    size: "96KB",
    format: "MP3",
    createTime: "2023-07-10",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",
  },
  {
    id: "4",
    title: "背景音乐 - 轻松愉快",
    duration: 120,
    size: "1.2MB",
    format: "MP3",
    createTime: "2023-08-05",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3",
  },
  {
    id: "5",
    title: "通知提醒音效",
    duration: 5,
    size: "64KB",
    format: "MP3",
    createTime: "2023-09-18",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3",
  },
  {
    id: "6",
    title: "电话铃声",
    duration: 15,
    size: "180KB",
    format: "MP3",
    createTime: "2023-10-30",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3",
  },
  {
    id: "7",
    title: "倒计时音效",
    duration: 60,
    size: "540KB",
    format: "MP3",
    createTime: "2023-11-12",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3",
  },
  {
    id: "8",
    title: "警告提示音",
    duration: 10,
    size: "112KB",
    format: "MP3",
    createTime: "2023-12-25",
    url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3",
  },
];

// 格式化时间（秒 -> mm:ss）
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

export default function AudioManagement() {
  // 状态管理
  const [audioList, setAudioList] = useState(mockAudioData);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [searchText, setSearchText] = useState("");
  const [currentAudio, setCurrentAudio] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState({});

  // 音频元素引用
  const audioRef = useRef(null);

  // 处理音频播放
  const handlePlayAudio = (audio) => {
    if (currentAudio && currentAudio.id === audio.id) {
      // 如果点击的是当前正在播放的音频，则切换播放/暂停状态
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
    } else {
      // 如果点击的是新的音频
      setCurrentAudio(audio);
      setIsPlaying(true);

      // 如果已经有音频元素，先重置
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
      }

      // 创建新的音频元素
      const newAudio = new Audio(audio.url);
      audioRef.current = newAudio;

      // 设置事件监听
      newAudio.addEventListener("timeupdate", () => {
        const currentProgress =
          (newAudio.currentTime / newAudio.duration) * 100;
        setProgress((prev) => ({
          ...prev,
          [audio.id]: currentProgress,
        }));
      });

      newAudio.addEventListener("ended", () => {
        setIsPlaying(false);
        setProgress((prev) => ({
          ...prev,
          [audio.id]: 0,
        }));
      });

      // 播放音频
      newAudio.play().catch((error) => {
        console.error("播放音频失败:", error);
        message.error("播放音频失败，请稍后重试");
        setIsPlaying(false);
      });
    }
  };

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    setCurrentPage(1);
  };

  // 处理分页变化
  const handlePageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  // 过滤音频列表
  const filteredAudioList = audioList.filter((audio) =>
    audio.title.toLowerCase().includes(searchText.toLowerCase())
  );

  // 分页后的音频列表
  const paginatedAudioList = filteredAudioList.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // 处理编辑音频
  const handleEditAudio = (audio) => {
    message.info(`编辑音频: ${audio.title}`);
  };

  // 处理删除音频
  const handleDeleteAudio = (audio) => {
    message.success(`删除音频: ${audio.title}`);
    setAudioList(audioList.filter((item) => item.id !== audio.id));
  };

  // 处理下载音频
  const handleDownloadAudio = (audio) => {
    message.info(`下载音频: ${audio.title}`);
    // 实际应用中，这里应该触发文件下载
    window.open(audio.url, "_blank");
  };

  // 清理音频播放器
  useEffect(() => {
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, []);

  // 渲染音频卡片
  const renderAudioCard = (audio) => {
    const isCurrentPlaying =
      currentAudio && currentAudio.id === audio.id && isPlaying;
    const currentProgress = progress[audio.id] || 0;

    return (
      <div key={audio.id} className={styles.audioCard}>
        <div className={styles.audioIcon}>
          <Waveform isPlaying={isCurrentPlaying} />
        </div>
        <div className={styles.cardContent}>
          <div className={styles.audioTitle} title={audio.title}>
            {audio.title}
          </div>
          <div className={styles.audioInfo}>
            {audio.format} · {audio.size} · {audio.createTime}
          </div>
          <div className={styles.audioControls}>
            <button
              className={styles.playButton}
              onClick={() => handlePlayAudio(audio)}
            >
              {isCurrentPlaying ? (
                <PauseCircleOutlined />
              ) : (
                <PlayCircleOutlined />
              )}
            </button>
            <div className={styles.progressContainer}>
              <div
                className={styles.progressBar}
                style={{
                  width: `${
                    currentAudio && currentAudio.id === audio.id
                      ? currentProgress
                      : 0
                  }%`,
                }}
              ></div>
            </div>
          </div>
          <div className={styles.timeInfo}>
            <span>
              {currentAudio && currentAudio.id === audio.id
                ? formatTime(audioRef.current?.currentTime || 0)
                : "00:00"}
            </span>
            <span>{formatTime(audio.duration)}</span>
          </div>
          <div className={styles.cardActions}>
            <Tooltip title="编辑">
              <Button
                type="text"
                icon={<EditOutlined />}
                onClick={() => handleEditAudio(audio)}
              />
            </Tooltip>
            <Tooltip title="下载">
              <Button
                type="text"
                icon={<DownloadOutlined />}
                onClick={() => handleDownloadAudio(audio)}
              />
            </Tooltip>
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDeleteAudio(audio)}
              />
            </Tooltip>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Title level={2} className={styles.title}>
          声音管理
        </Title>
        <div className={styles.searchContainer}>
          <Search
            placeholder="搜索音频..."
            allowClear
            onSearch={handleSearch}
            style={{ width: 250 }}
          />
          <Button type="primary" icon={<PlusOutlined />}>
            上传音频
          </Button>
        </div>
      </div>

      {paginatedAudioList.length > 0 ? (
        <>
          <div className={styles.cardGrid}>
            {paginatedAudioList.map((audio) => renderAudioCard(audio))}
          </div>

          <div className={styles.pagination}>
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={filteredAudioList.length}
              onChange={handlePageChange}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 条`}
            />
          </div>
        </>
      ) : (
        <div className={styles.emptyContainer}>
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无音频" />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            className={styles.uploadButton}
          >
            上传音频
          </Button>
        </div>
      )}
    </div>
  );
}
